<?php
declare (strict_types = 1);

namespace app\service\controller;

use app\BaseController;
use app\logic\crontab\Token;
use think\App;
use think\Exception;
use think\facade\Config;
use think\Request;
use \app\model\Shop;

class Authorization extends BaseController
{
    /**
     * 獲取平台授权地址
    */
   public function authUrl(Request $request) {
       $shop_id = $request->get('shop_id');
       if (empty($shop_id)) {
           return $this->error('商店id不能为空');
       }
       $shop = Shop::find($shop_id);
       if (empty($shop)) {
           return $this->error('商店不存在', [], 404);
       }
       if (empty($shop->params)) {
           return $this->error('网店参数未填写');
       }
       //路由到不同的平台方法获取授权url
       $code = Config::get("tap.platform.{$shop->platform_id}.code");
       $method = "{$code}AuthUrl";
       if (empty($code) || !method_exists($this, $method)) {
           return $this->error('暂不支持该平台授权');
       }
       $url = call_user_func_array([$this, $method], [$shop]);
       return $this->repData($url);
   }

   /**
    * 微盟授權地址
   */
    private function weimengAuthUrl(Shop $shop) {
        if (empty($shop->params->client_id) || empty($shop->params->client_secret)) {
            abort($this->error('client_id或client_secret不能为空'));
        }
        $redirect_uri = url('/weimeng', [], true, true)->build();
        $query = [
            'enter' => 'wm',
            'view' => 'pc',
            'response_type' => 'code',
            'scope' => 'default',
            'client_id' => $shop->params->client_id,
            'redirect_uri' => $redirect_uri,
            'state' => $shop->id,
            'time' => time()
        ];
        return 'https://dopen.weimob.com/fuwu/b/oauth2/authorize?' . http_build_query($query);
    }

    /**
     * 刷新token
    */
    public function refreshToken(Request $request, App $app) {
        $shop_id = $request->get('shop_id');
        if (empty($shop_id)) {
            return $this->error('商店id不能为空');
        }
        $shop = Shop::find($shop_id);
        if (empty($shop)) {
            return $this->error('商店不存在', [], 404);
        }
        if (empty($shop->params)) {
            return $this->error('网店参数未填写');
        }
        //路由到不同的平台方法获取刷新token
        $code = Config::get("tap.platform.{$shop->platform_id}.code");
        if (empty($code)) {
            return $this->error('暂不支持该平台刷新token');
        }
        $method = "get{$code}Token";
        try {
            $ret = $app->invokeMethod([Token::class, $method], [$shop]);
            return json($ret);
        } catch (Exception $e) {
            return $this->error('暂不支持该平台刷新token');
        }
    }
}
